package ec.edu.ups.cidi.siia.plamdep.frontend.utils;

import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Iterator;
import java.util.List;

import javax.faces.context.FacesContext;
import javax.imageio.ImageIO;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.json.JSONArray;
import org.json.JSONObject;

import ec.edu.ups.cidi.siia.plamdep.frontend.controlador.AnalisisBean;
import ec.edu.ups.cidi.siia.plamdep.frontend.modelo.Archivo;

@WebServlet(name="ServletSubirMultipleArchivo",urlPatterns="/uploadMultiple/*")
public class ServletUploadMultiple extends HttpServlet {
        
    /**
        * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
        * 
        */
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        
    	/*
    	 Iterator<String> it = request.getParameterMap() .keySet().iterator();
    	String n=null;
    	while (it.hasNext()) {
    			n=it.next(); //en n tenemos la clave
    			System.out.println("Params: "+n+"    value:"+ request.getParameterMap().get(n));
    			   	
    	}
    		*/
    	
    	if (request.getParameter("getfile") != null && !request.getParameter("getfile").isEmpty()) {
          File file = new File("/opt/"+request.getParameter("getfile"));             

          
          if (file.exists()) {
              int bytes = 0;
              ServletOutputStream op = response.getOutputStream();

              response.setContentType(getMimeType(file));
              response.setContentLength((int) file.length());
              response.setHeader( "Content-Disposition", "inline; filename=\"" + file.getName() + "\"" );

              byte[] bbuf = new byte[1024];
              DataInputStream in = new DataInputStream(new FileInputStream(file));

              while ((in != null) && ((bytes = in.read(bbuf)) != -1)) {
                  op.write(bbuf, 0, bytes);
              }

              in.close();
              op.flush();
              op.close();
          }
      }
        
    }
    
    /**
        * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
        * 
        */
    @SuppressWarnings("unchecked")
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	
    	AnalisisBean sesionFiles =null;
    	
    	/** Accede al Bean ********/
		try {
			InitialContext  ic = new InitialContext();
			sesionFiles =(AnalisisBean) request.getSession().getAttribute("analisisBean");
			if (sesionFiles  == null) 
			{
				   sesionFiles  = new AnalisisBean();
				   request.getSession().setAttribute("analisisBean", sesionFiles);
			}
			
		} catch (NamingException e1) {	e1.printStackTrace();	}
		/** Accede al Bean ********/
         

        
        if (!ServletFileUpload.isMultipartContent(request)) {
            throw new IllegalArgumentException("Request is not multipart, please 'multipart/form-data' enctype for your form.");
        }

        ServletFileUpload uploadHandler = new ServletFileUpload(new DiskFileItemFactory());
        JSONArray json = new JSONArray();
        
        

        try {
            List<FileItem> items = uploadHandler.parseRequest(request);
            for (FileItem item : items) {
                if (!item.isFormField()) {
                	
                	String path=System.getProperty("plamdep.resources.path")+"/documentos_repositorio/"+item.getName();
                    //File file = new File("/opt/",item.getName());
                	File file = new File(path);	
                    Archivo ar=new Archivo();
                    ar.setRuta(path);
                    ar.setArchivo(item);
                    sesionFiles.addFiles(ar);
                    item.write(file);
                    

		            JSONObject jsono = new JSONObject();
		            jsono.put("name", item.getName());
		            jsono.put("size", item.getSize());
		            jsono.put("url", "uploadMultiple?getfile=" + item.getName());
		            jsono.put("thumbnail_url", "resources/imagenes/thumb.jpg" );
		            jsono.put("delete_url", "" );
		            jsono.put("delete_type", "GET");
		            System.out.println(jsono.toString());
		            json.put(jsono);

                    
                       
                }
            }
        } catch (FileUploadException e) {
                throw new RuntimeException(e);
        } catch (Exception e) {
                throw new RuntimeException(e);
        } finally {
           	PrintWriter writer = response.getWriter();
            response.setContentType("application/json");
            //JSONArray json = new JSONArray();
            /*for (FileItem item : sesionFiles.getFiles()) 
        	{
		      
		            JSONObject jsono = new JSONObject();
		            jsono.put("name", item.getName());
		            jsono.put("size", item.getSize());
		            jsono.put("url", "uploadMultiple?getfile=" + item.getName());
		            jsono.put("thumbnail_url", "resources/imagenes/thumb.jpg" );
		            jsono.put("delete_url", "" );
		            jsono.put("delete_type", "GET");
		            System.out.println(jsono.toString());
		            json.put(jsono);
		      
        	}
        	*/
        	writer.write(json.toString());
        	
            writer.close();
        }

    }
    
    
    private String getMimeType(File file) {
        String mimetype = "";
        if (file.exists()) {
            if (getSuffix(file.getName()).equalsIgnoreCase("png")) {
                mimetype = "image/png";
            }else if(getSuffix(file.getName()).equalsIgnoreCase("jpg")){
                mimetype = "image/jpg";
            }else if(getSuffix(file.getName()).equalsIgnoreCase("jpeg")){
                mimetype = "image/jpeg";
            }else if(getSuffix(file.getName()).equalsIgnoreCase("gif")){
                mimetype = "image/gif";
            }else {
                javax.activation.MimetypesFileTypeMap mtMap = new javax.activation.MimetypesFileTypeMap();
                mimetype  = mtMap.getContentType(file);
            }
        }
        return mimetype;
    }
    private String getSuffix(String filename) {
        String suffix = "";
        int pos = filename.lastIndexOf('.');
        if (pos > 0 && pos < filename.length() - 1) {
            suffix = filename.substring(pos + 1);
        }
        return suffix;
    }


}